
package com.lxr.test5002;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.lxr.test5002.base.BaseActivity;
import com.lxr.test5002.base.Constants;
import com.lxr.test5002.base.ThreadPool;
import com.lxr.test5002.utils.MyUtil;
import com.lxr.test5002.utils.RefreshViewUtils;
import com.sdk.devicemanager.Barcode;
import com.sdk.devicemanager.BarcodeConfig;

import butterknife.BindView;

/**
 * 类描述:[扫描测试]
 * 说明:为降低功耗，条码头可控制下电，如需广播接收条码信息，触发扫描前，需重新给条码上电
 * 目前提供两种扫描方式 （只能二选一）
 * 1、接口方式
 * 2、系统按键扫描+广播回调方式
 *
 * @author: LXR-zsm
 * @Date: 2023/12/18 10:52
 */
public class ScanActivity extends BaseActivity {
    @BindView(R.id.btn_scan_start)
    Button mBtnScan;
    @BindView(R.id.tv_scan_tip)
    TextView mTvScanTip;
    @BindView(R.id.rg_scan)
    RadioGroup rgScan;
    @BindView(R.id.rb_api)
    RadioButton rbApi;
    @BindView(R.id.rb_key)
    RadioButton rbKey;
    /**
     * 条码设备控制类
     */
    private Barcode mBarcode;

    private boolean destroy;

    private int scanModel = 0;

    public ScanActivity() {
        super(R.layout.activity_barcode);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

    }


    @Override
    protected void initData() {
        //条码控制类
        mBarcode = new Barcode(ScanActivity.this);

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (scanModel == 0) {
            mBarcode.cancel1D();
        }
        destroy = true;
    }


    @Override
    protected void initEvent() {
        rgScan.setOnCheckedChangeListener((group, checkedId) -> {
            Log.i(Constants.LOG_TAG, "选择：" + checkedId);
            mTvScanTip.setText("");
            if (checkedId == rbApi.getId()) {
                scanModel = 1;
                mBtnScan.setVisibility(View.VISIBLE);
            } else {
                mBtnScan.setVisibility(View.GONE);
                scanModel = 2;
            }
            initStup();
        });

        mBtnScan.setOnClickListener(v -> {
            mBtnScan.setEnabled(false);
            mTvScanTip.setText("");
            new ScanThread().start();
        });
    }

    boolean isRegister;

    public void initStup() {
        ThreadPool.getInstance().execute(() -> {
            //条码配置扫描模式参数
            BarcodeConfig mBarcodeConfig = new BarcodeConfig();
            /**
             * 输出模式
             * 1：OUTPUT_DIRECT 填充模式，直接填充到文本框
             * 2：OUTPUT_VIRTUAL_KEY  模拟键盘
             * 3：OUTPUT_API   api获取
             */
            mBarcodeConfig.mOutPutMode = BarcodeConfig.OUTPUT_API;
            /**
             * 编码
             * 1：ENCODE_MODE_UTF8  utf-8
             * 2：ENCODE_MODE_GBK   gbk
             */
            mBarcodeConfig.mEncodeMode = BarcodeConfig.ENCODE_MODE_UTF8;
            /**
             * 触发模式
             * 0：TRIGGER_MODE_MANUAL  手动触发模式
             * 1：TRIGGER_MODE_CONTINUOUS  连续触发模式 --- 暂未实现
             * 2：TRIGGER_MODE_SINGLE  单触发模式
             */
            mBarcodeConfig.mTrigerMode = BarcodeConfig.TRIGGER_MODE_MANUAL;
            mBarcodeConfig.mAutoEnt = 0;
            mBarcode.setup1D(mBarcodeConfig);
            if (scanModel == 1) {
                //接口方式必须关闭系统按键扫描、并取消广播监听
                mBarcode.setKeyenable(false);
                if (isRegister) {
                    Intent intent = new Intent("android.intent.scanner.CONFIG");
                    int state = 1000;
                    intent.putExtra("state", state);
                    sendBroadcast(intent);
                    unregisterReceiver(mReceiver);
                    isRegister = false;
                }

            } else {
                //打开系统按键触发扫码
                mBarcode.setKeyenable(true);
                if (!isRegister) {
                    //监听广播回调
                    IntentFilter mFilter = new IntentFilter("ACTION_BAR_SCAN");
                    registerReceiver(mReceiver, mFilter);
                    isRegister = true;
                    Intent intent = new Intent("android.intent.scanner.CONFIG");
                    int state = 1001;
                    intent.putExtra("state", state);
                    sendBroadcast(intent);
                }
            }
        });
    }

    /**
     * 广播方式回调结果
     */
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String scanData = intent.getStringExtra("EXTRA_SCAN_DATA");
            RefreshViewUtils.appendText(ScanActivity.this, mTvScanTip, "广播扫描：" + scanData);
            //用户按键取消扫描，也会返回提示数据，需自行过滤
            //例如：stop by user、scanner timeout、fail
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroy = true;
        if (isRegister) {
            Intent intent = new Intent("android.intent.scanner.CONFIG");
            int state = 1000;
            intent.putExtra("state", state);
            sendBroadcast(intent);
            unregisterReceiver(mReceiver);
        }
    }

    /**
     * 类描述:[扫描操作顺序说明]
     * 说明:  接口扫描方式
     * 条码上电：open1D()
     * 条码配置：setup1D() 如无需特殊要求，可不配置
     * 开始扫描：scan1D()
     * 取消扫描：cancel1D()
     * 条码下电：close1D()
     *
     * @author: LXR-zsm
     * @Date: 2023/12/19 10:34
     */
    private class ScanThread extends Thread {
        @Override
        public void run() {
            //1\打开条码设备
            boolean open = mBarcode.open1D();
            if (destroy) {
                mBarcode.close1D();
                return;
            }
            RefreshViewUtils.appendText(ScanActivity.this, mTvScanTip,
                    "打开条码：" + (open ? "成功" : "失败"));

            if (open) {
                String result = mBarcode.scan1D();
                RefreshViewUtils.appendText(ScanActivity.this, mTvScanTip, "接口扫描：" +
                        (MyUtil.isValueEmpty(result) ? "失败" : result));
            }

            boolean close = mBarcode.close1D();
            RefreshViewUtils.appendText(ScanActivity.this, mTvScanTip, "条码关闭：" +
                    (close ? "成功" : "失败"));
            runOnUiThread(() -> mBtnScan.setEnabled(true));
        }
    }

}